#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <unistd.h>
#include <cstddef>

using namespace std;

class Data
{
public:
    Data(){}
    ~Data(){}

    int getData() const{ return _data; }
private:
    int _data = 10;
};

class MiddleLayer
{
public:
    MiddleLayer(Data * p): _pdata(p){}

    ~MiddleLayer(){
        cout << "~MiddleLayer()" << endl;
        if(_pdata){
            delete _pdata;
            _pdata = nullptr;
        }
    }
    Data *operator->(){
        return _pdata;
    }
    Data &operator*(){
        return *_pdata;
    }
private:
    Data * _pdata;
};

class ThirdLayer{
public:
    ThirdLayer(MiddleLayer * ml):_ml(ml)
    {
        cout << "ThirdLayer(MiddleLayer *)" << endl;
    }

    ~ThirdLayer(){
        cout << "~ThirdLayer()" << endl;
        if(_ml){
            delete _ml;
            _ml = nullptr;
        }
    }
    MiddleLayer &operator->(){
        return *_ml;
    }
    Data &operator*(){
        return **_ml;
    }

private:
    MiddleLayer * _ml;
};

int main()
{
    ThirdLayer t(new MiddleLayer(new Data()));
    //MiddleLayer m(MiddleLayer(new Data()));
    cout<< t->getData() << endl;
    cout<< (*t).getData() << endl;

    return 0;
}

